var form;
var table;
var layer;
var upload;
var $;
var path;
var img;
var a=0;
var arr=[];
var arr2=[];
var delImg=[];
var noDelImg=[];
layui.use(['table','element','layer','upload'],function(){
    form = layui.form;
    table=layui.table;
    layer=layui.layer;
    upload=layui.upload;
    $=layui.$;

    edit();

    //修改主图
    var uploadInst = upload.render({
        elem: '#test1' //绑定元素
        ,url: '/SyOperationController/uoloadImg' //上传接口
        ,done: function(res, index, upload){

            //截取查询出，删除图片
            var url=$("#img").attr("src");
            var delUrl=url.substr(url.lastIndexOf(':')+2);
            var jsonUrl={"delImg":delUrl};
            delImg.push(jsonUrl);

            $("#url").val(res.src);
            $("#img").remove();
            $("#mainImage").append("<img id='img' src='"+res.src+"' class='microcircleImg1'>");
            layer.msg("修改成功", {icon:1});

            //截取查询出，删除图片
            var url2=$("#img").attr("src");
            var delUrl2=url2.substr(url2.lastIndexOf(':')+2);
            var jsonUrl2={"delImg":delUrl2};
            noDelImg.push(jsonUrl2);
        }
        ,error: function(){
            //请求异常回调
        }
    });

    //添加预览图
    var uploadInst2 = upload.render({
        elem: '#test2' //绑定元素
        ,url: '/SyOperationController/uoloadImg' //上传接口
        ,done: function(res, index, upload){

            //获取当前登陆人员的信息
            var create=localStorage.getItem("user");
            create=JSON.parse(create);//将获取json字符串转json对象

            var courseId=$("#productId").val();
            var courseName=$("#productName").val();

            $("#mainImage1").append("<p id='pId'><img src='"+res.src+"'class='microcircleImg'/><i class='layui-icon layui-icon-close' id='iId' value='"+a+"'  onclick='deleteBtn2(this,\""+res.src+"\")' title='删除图片'></i></p>");

            //截取添加到数组
            var arrayImgs=res.src;
            var url=arrayImgs.substr(arrayImgs.lastIndexOf(':')+2);

            var jsonUrl2={"delImg":url};
            noDelImg.push(jsonUrl2);

            var json={"pictureUrl":url,"num":a,"createUser":create.user_id,"pictureType":1,"courseId":courseId,"courseName":courseName};
            arr2.push(json);

            //每次添加a都加一，用于删除时获取下标
            a++;
        }
        ,error: function(){
            //请求异常回调
        }
    });

});

/*日期转换*/
function settime(da){
    var date=new Date(da);
    var year=date.getFullYear();
    var month=date.getMonth()+1;
    var day=date.getDate();
    var hours=date.getHours();
    var mm=date.getMinutes();
    var s=date.getSeconds();
    //return year+'-'+add(month)+'-'+add(day)+' '+add(hours)+':'+add(mm)+':'+add(s);
    return year+'-'+month+'-'+day+' '+hours+':'+mm+':'+s;
};

function edit(){
    var productId = localStorage.getItem("productId");
    $('input[name=productId]').val(productId); //商品ID
    $.ajax({
        url: "/SyOperationController/selProducts",
        type: "post",
        dataType: "json",
        data: {"productId": productId},
        success: function (data) {
            path=data.data.path;  //路径
            img=data.data.img;  //图片名

            $("#productCode").val(data.data.productCode);  //编号
            $("#productName").val(data.data.productName);  //名称
            $("#currentpriceProduct").val(data.data.currentpriceProduct); //现价
            $("#originalpriceProduct").val(data.data.currentpriceProduct); //原价
            $("#url").val(data.data.mainImage);  //主图

            /*var date=data.data[0].create_date;
            date = date.slice(0, date.indexOf("."));
            createDate = date.replaceAll('T',' ');*/

            var Date =  settime(data.data.createDate);
            $("#createDate").val(Date);  //时间
            $("#createUser").val(data.data.trueName);  //上传人
            $("#createId").val(data.data.userId);  //上传人Id
            $("#categroyName").val(data.data.categroyName);  //分类
            $("#categoryId").val(data.data.categoryId);  //分类Id
            var productSate;
            if(data.data.productSate==2){
                productSate="待审核";
            }else if(data.data.productSate==3){
                productSate="审核通过";
            }else if(data.data.productSate==4){
                productSate="审核未通过";
            }else{
                productSate="其他";
            }
            $("#productSate").val(productSate);  //审核状态
            $("#productLabel").val(data.data.productLabel);  //商品标签
            $("#searchKeywords").val(data.data.searchKeywords);  //关键字
                if(data.data.fabulous==null){
                    data.data.fabulous=0;
                }
            $("#fabulous").val(data.data.fabulous);  //点赞量

                if(data.data.collectionVolume==null){
                    data.data.collectionVolume=0;
                }
            $("#collectionVolume").val(data.data.collectionVolume);  //收藏量

                if(data.data.productSales==null){
                    data.data.productSales=0;
                }
            $("#productSales").val(data.data.productSales);  //销量
            $("#productDescription").val(data.data.productDescription);  //简介
            $('#mainImage').html("<img id='img' src='"+data.data.mainImage+"' class='microcircleImg1'>"); //主图
            //循环预览图
            for(var a=0;a<data.data.microcircleImg.length;a++){

                $("#mainImage1").append("<p id='pId'><img src='"+data.data.microcircleImg[a].picture_url+"'class='microcircleImg'/> <i class='layui-icon layui-icon-close' id='iId'onclick='deleteBtn(this,\""+data.data.microcircleImg[a].picture_url+"\")' value='"+data.data.microcircleImg[a].picture_id+"' title='删除图片'></i></p>")
            }

        }
    })
}

//选择分类
function selCouCategory() {
    layer.open({
        type:2,
        title:"分类详情",
        area:['300px','400px'],
        shade:0.4,
        offset:'auto',
        content:"ProductUpdate_tree.html",
        success:function(layero,index){
        }
    })
    window.layer_2=layer;
}


//确定修改
function determine(){
    var productId=$('input[name=productId]').val();//商品ID
    var productName=$('input[name=productName]').val();//商品名称
    var cPro=$('input[name=currentpriceProduct]').val();//商品现价
    var oPro=$('input[name=originalpriceProduct]').val();//商品原价
    var categoryId=$('input[name=categoryId]').val();//商品分类ID
    var productLabel=$('input[name=productLabel]').val();//商品标签
    var url=$('input[name=url]').val(); //商品主图
    var sKey=$('input[name=searchKeywords]').val();//商品关键字
    var pDes=$('textarea[name=productDescription]').val();//商品简介
    //获取当前登陆人员的信息
    var create=localStorage.getItem("user");
    create=JSON.parse(create);//将获取json字符串转json对象

    var img=url.substr(url.lastIndexOf(':')+2);

    var formData ={"productId":productId,"productName":productName,"currentpriceProduct":cPro,"originalpriceProduct":oPro,"categoryId":categoryId,
        "productLabel":productLabel,"searchKeywords":sKey,"productDescription":pDes,"createUser":create.user_id,"updateUser":create.user_id,"mainImage":img,"type":3};
    formData.str=JSON.stringify(arr);
    formData.strAdd=JSON.stringify(arr2);

    //删除服务器课程主图
    formData.delImg=JSON.stringify(delImg);
    console.log(formData.delImg)

    $.ajax({
        url: "/SyOperationController/updProduct",
        type: "post",
        dataType: "json",
        data:formData,
        success: function (data) {
            if(data.code==0){
                layer.msg("修改成功");
                parent.location.reload();
                var layer_1=parent.layer_1;
                layer_1.close(layer_1.index);
            }else{
                layer.msg("修改失败");
            }
        }

    });
}

//取消并删除服务器上传多余图片
function cancels() {
    if(noDelImg.length>0){
        $.ajax({
            url:"/SyteacherSelController/noDelImg",
            type:"post",
            dataType:"json",
            traditional: true,
            data:{"noDelImg":JSON.stringify(noDelImg)},
            success:function(data){
                var layer_1=parent.layer_1;
                layer_1.close(layer_1.index);
            }
        });
    }else{
        var layer_1=parent.layer_1;
        layer_1.close(layer_1.index);
    }
}

//点击删除，把预览图id放入数组
var deleteBtn = function(obj,url){
    var arrayImgs=url;
    var delUrl=arrayImgs.substr(arrayImgs.lastIndexOf(':')+2);
    var json={"delImg":delUrl};
    delImg.push(json);

    obj.parentElement.remove();
    var id = obj.getAttribute('value');
    json={"pictureId":id};
    arr.push(json);
};

//添加时，删掉预览图片
var deleteBtn2 = function(obj,url){
    var arrayImgs=url;
    var delUrl=arrayImgs.substr(arrayImgs.lastIndexOf(':')+2);

    var json={"delImg":delUrl};
    noDelImg.push(json);

    obj.parentElement.remove();
    var id = obj.getAttribute('value');
    //根据num值，获取下标，进行删除
    var index=arr2.findIndex((element)=>(element.num ==id));
    arr2.splice(index,1);
};